package com.huluobo.sign.pages

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.UIState
import com.huluobo.lib_http.Const
import com.huluobo.sign.SignIntent
import com.huluobo.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.time.LocalTime
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/6/2.
 */
//高德地图本体
lateinit var map: AMap

//展示地图的View
lateinit var mapView: MapView

//定位展示器
lateinit var myLocationStyle: MyLocationStyle

//地理位置信息检索
lateinit var geocodeSearch: GeocodeSearch

//解析地理位置信息
lateinit var query: RegeocodeQuery

//计时器
lateinit var timer: Timer

@Composable
fun SignCommitPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {

    //上班打卡显示时间,默认是一个字符串
    var startTIme by remember {
        mutableStateOf("上班还未打卡")
    }

    //下班打卡显示时间
    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }

    //按钮文字
    var btnName by remember {
        mutableStateOf("上班打卡")
    }

    //按钮时间
    var nowTime by remember {
        mutableStateOf("00:00:00")
    }

    //控制按钮是否可以被点击,默认可点击,如果上下班卡都打完,当日不可再次点击
    var enable by remember {
        mutableStateOf(true)
    }

    //存取上下班打卡时间
    val kv = MMKV.defaultMMKV()

    var lat by remember {
        mutableStateOf(0.0)
    }

    var lon by remember {
        mutableStateOf(0.0)
    }

    var address by remember {
        mutableStateOf("")
    }

    var type by remember {
        mutableStateOf("")
    }

    var status by remember {
        mutableStateOf("")
    }

    //由于计时器是个耗时操作,所以需要开启协程在子线程中运行
    LaunchedEffect(key1 = "", block = {
        //计时器的协程,用于更新当前按钮上的时间
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                nowTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            }, 0, 1000)
        }

        //处理上下班存取的逻辑
        launch {
            //取出上班打卡时间,如果没取到就为空
            val signTime = kv.decodeString(Const.PARAM_SIGN_IN, "").toString()
            //判断上班打卡是否为空
            if (!TextUtils.isEmpty(signTime)) {
                //如果不为空,获取当前日期
                val time = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                val statusIn = kv.decodeString(Const.PARAM_STATUS_IN).toString()
                //由于保存的打卡时间是精确到时分秒的,所以需要截取字符串
                //2025-06-02 15:55:00  保存的打卡时间
                //2025-06-02
                val signDate = signTime.substring(0, 10)
                //判断当前日期和kv中保存的日期是否相等,如果相等证明今天打过卡,需要在页面上赋值
                if (time == signDate) {
                    //如果kv中取出的日期等于当前日期,证明打过卡
                    startTIme = "上班时间 : $signTime $statusIn"
                    //同时,按钮文字赋值为下班打卡,咱们通过按钮的文字来判断打上班卡还是下班卡,保存上班时间还是下班时间
                    btnName = "下班打卡"
                    //取出下班卡
                    val outTime = kv.decodeString(Const.PARAM_SIGN_OUT, "").toString()
                    //判断下班卡是否为空
                    if (!TextUtils.isEmpty(outTime)) {
                        val statusOut = kv.decodeString(Const.PARAM_STATUS_OUT).toString()
                        //如果不为空,需要判断是否为今天,截取下班卡的日期
                        val outDate = outTime.substring(0, 10)
                        //对比是否是今天
                        if (time == outDate) {
                            //如果是今天,下班卡赋值
                            endTime = "下班时间 : $outTime $statusOut"
                            //设置按钮不可点击
                            enable = false
                        }
                    }
                } else {
                    //如果日期不等,则今天还没打过卡,重新给按钮赋值为初始化状态
                    btnName = "上班打卡"
                }
            }
        }

        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "提交签到信息失败:${it.msg}")
                        ToastUtils.showLong("提交签到信息失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        ToastUtils.showLong("签到/签退成功")
                    }
                }
            }
        }
    })

    Column(Modifier.padding(10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        BaseTitle(title = "签到/签退", navHostController = navHostController)
        Button(onClick = {
            kv.remove(Const.PARAM_SIGN_IN)
            kv.remove(Const.PARAM_SIGN_OUT)
        }) {
            Text(text = "清空kv")
        }
        AndroidView(modifier = Modifier.height(300.dp), factory = {
            //AndroidView 特点,需要在factory中最后一句返回出一个View
            //new出地图,实例化
            mapView = MapView(it)
            //设置地图的初始化
            mapView.onCreate(null)
            //获取地图编年体
            map = mapView.map
            //new出定位控件
            myLocationStyle = MyLocationStyle()
            //设置定位的刷新时间
            myLocationStyle.interval(2000)
            //添加定位控件到地图上
            map.myLocationStyle = myLocationStyle
            //打开定位开关
            map.isMyLocationEnabled = true

            //添加位置改变监听器
            map.addOnMyLocationChangeListener { location ->
                //实例化地理位置搜索
                geocodeSearch = GeocodeSearch(BaseApp.context)
                //解析地理位置,通过经纬度查询位置信息,第一个参数是一个坐标点,包含经纬度,扫描的频次,扫描的模式
                query = RegeocodeQuery(LatLonPoint(location.latitude, location.longitude), 2000f, GeocodeSearch.AMAP)
                geocodeSearch.getFromLocationAsyn(query)
                //设置检索的监听器
                geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(result: RegeocodeResult?, error: Int) {
                        lon = location.longitude
                        lat = location.latitude
                        address = result?.regeocodeAddress?.formatAddress.toString()
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                    }
                })
            }
            //返回出地图
            mapView
        })

        Spacer(modifier = Modifier.height(height = 50.dp))
        Text(
            text = startTIme,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(10.dp))
        Text(
            text = endTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Button(
            modifier = Modifier
                .size(140.dp)
                .clip(CircleShape), onClick = {
                val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                val workStart = "08:30:00"
                val workEnd = "17:00:00"
                if (btnName == "上班打卡") {
                    kv.encode(Const.PARAM_SIGN_IN, time)
                    status = if (time.substring(11, time.length) > workStart) "迟到" else "正常"
                    kv.encode(Const.PARAM_STATUS_IN, status)
                    startTIme = "上班时间 : $time $status"
                    btnName = "下班打卡"
                    type = "上班"
                    val map = mapOf(
                        Const.PARAM_LAT to lat,
                        Const.PARAM_LON to lon,
                        Const.PARAM_TYPE to type,
                        Const.PARAM_STATUS to status,
                        Const.PARAM_ADDRESS to address
                    )
                    vm.sendIntent(SignIntent.AddSign(map))
                } else {
                    kv.encode(Const.PARAM_SIGN_OUT, time)
                    status = if (time.substring(11, time.length) < workEnd) "早退" else "正常"
                    kv.encode(Const.PARAM_STATUS_OUT, status)
                    endTime = "下班时间 : $time $status"
                    enable = false
                    type = "下班"
                    val map = mapOf(
                        Const.PARAM_LAT to lat,
                        Const.PARAM_LON to lon,
                        Const.PARAM_TYPE to type,
                        Const.PARAM_STATUS to status,
                        Const.PARAM_ADDRESS to address
                    )
                    vm.sendIntent(SignIntent.AddSign(map))
                }
            }, enabled = enable
        ) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }
    }
}